package club.xyes.zkh.ecommerce.security.conf;

import club.xyes.zkh.ecommerce.security.LoginSuccessHandler;
import club.xyes.zkh.ecommerce.security.handler.LoginFailHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

/**
 * Create by 郭文梁 2019/4/15 0015 17:26
 * WebSecurityConfiguration
 * Web安全相关配置
 *
 * @author 郭文梁
 * @data 2019/4/15 0015
 */
@Configuration
public class WebSecurityConfiguration extends WebSecurityConfigurerAdapter {
    private final LoginSuccessHandler loginSuccessHandler;
    private final LoginFailHandler loginFailHandler;

    @Autowired
    public WebSecurityConfiguration(LoginSuccessHandler loginSuccessHandler, LoginFailHandler loginFailHandler) {
        this.loginSuccessHandler = loginSuccessHandler;
        this.loginFailHandler = loginFailHandler;
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable();
        http.authorizeRequests()
                .antMatchers("/static/**").permitAll().anyRequest().authenticated()
                .and().formLogin().loginPage("/login.html").loginProcessingUrl("/login").successHandler(loginSuccessHandler).failureHandler(loginFailHandler).permitAll()
                .and().logout().permitAll().invalidateHttpSession(true)
                .deleteCookies("JSESSIONID")
                .and().sessionManagement().maximumSessions(10).expiredUrl("/login");
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }
}
